package com.hmdp.utils;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;

/**
 * @author 小阳
 * @date 2025/10/22 11:25
 * @description 封装redis常用操作的组件
 * Version: 1.0
 */

@Component
public class CacheClient {


    private final StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void setWithExpire(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R queryWithPassThrough(String preFix, ID id, Class<R> type, Long time, TimeUnit unit, Function<ID, R> dbFallbackOperation){
        // 1. 查询redis
        String key = preFix + id;
        String JsonStr = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断是否存在
        if (StrUtil.isNotBlank(JsonStr)) {
            // 3. 存在，直接返回
            return JSONUtil.toBean(JsonStr, type);
        }
        // 4. 不存在
        // 4.1 查询数据库
        R r = dbFallbackOperation.apply(id);
        // 4.2 查到，保存到redis。返回
        if (r != null) {
            this.setWithExpire(key, r, time, unit);
            return r;
        }
        // 4.3 未查到，保存空值到redis，返回
        this.setWithExpire(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
        return null;
    }

    public <R,ID> R queryWithLogicalExpire(String preFix, ID id, Class<R> type, Long time, TimeUnit unit, Function<ID, R> dbFallbackOperation){
        // 1. 获取redis中的数据
        String key = preFix + id;
        String JsonStr = stringRedisTemplate.opsForValue().get(key);
        // 2. 为空，直接返回空值。热点数据会提前保存到redis。
        if(StrUtil.isBlank(JsonStr)){
            return null;
        }
        // 3. 不为空，解析数据。
        RedisData redisData = JSONUtil.toBean(JsonStr, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        // 4. 判断是否过期。
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            // 4.1 未过期，直接返回数据。
            return r;
        }
        // 4.2 过期，重建缓存。
        // 4.3 尝试获取锁
        String lockKey = "lock:" + key;
        if (BooleanUtil.isTrue(tryLock(lockKey))) {
            // 4.2 获取锁成功，重建缓存
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try{
                    R newR = dbFallbackOperation.apply(id);
                    this.setWithLogicalExpire(key, newR, time, unit);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally{
                    // 释放锁
                    unlock(lockKey);
                }
            });
        }
        // 4.3 获取锁失败，返回旧数据
        // 5. 缓存未命中，查询数据库
        return r;

    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

}
